package com.sf.proxy.server;

import com.sf.proxy.handler.HttpRequestHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultThreadFactory;

public class HttpServer {




  public void start(int port) {
    NioEventLoopGroup worker = new NioEventLoopGroup(1,new DefaultThreadFactory("work", Thread.MAX_PRIORITY));
    NioEventLoopGroup boss = new NioEventLoopGroup(1,new DefaultThreadFactory("boss", Thread.MAX_PRIORITY));
    try {
      ServerBootstrap b = new ServerBootstrap();
      b.group(boss, worker)
          .channel(NioServerSocketChannel.class)
//          .option(ChannelOption.SO_BACKLOG, 100)
          .handler(new LoggingHandler(LogLevel.DEBUG))
          .childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
              ch.pipeline().addLast("httpCodec", new HttpServerCodec());
              ch.pipeline().addLast("httpObject",new HttpObjectAggregator(Integer.MAX_VALUE));
              ch.pipeline().addLast("serverHandle",
                  new HttpRequestHandler());
            }
          });
      ChannelFuture f = b
          .bind(port)
          .sync();
      f.channel().closeFuture().sync();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      worker.shutdownGracefully();
      boss.shutdownGracefully();
    }
  }

}
